package com.bit.spring.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
public class UserController {

    @PostMapping("/login")
    public Boolean login(String userName, String password, HttpSession session){
        /**
         * 1. 参数校验(基本校验, 是否为空, 参数范围....)
         * 2. 判断密码是否正确
         */
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return false;
        }
        //TODO 当前未学习数据库的操作, 暂且写死  硬编码
        if ("admin".equals(userName) && "admin".equals(password)){
            //存储session
            session.setAttribute("loginUser", userName);
            return true;
        }

//        if (StringUtils.hasLength(userName) && StringUtils.hasLength(password)){
//            if ("admin".equals(userName) && "admin".equals(password)){
//                return true;
//            }
//        }
        return false;

    }


    @GetMapping("/getLoginUser")
    public String getLoginUser(HttpServletRequest request){
        //参数为false, 获取的session为null时, 不会创建session
        HttpSession session = request.getSession(false);
        if (session!=null){
            String loginUser = (String)session.getAttribute("loginUser");
            return loginUser;
        }
        return "";
    }
}
